package com.ete.service.db

import android.app.Application
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
import com.ete.service.db.dao.HardwareInfoDao
import com.ete.service.entry.hardware.HardwareInfoEntry

/**
 * Author:LiXian
 * <p>
 * Desc:数据库
 * Version:1.0
 * date 2024/1/22 14:14
 */
@Database(
        entities = [HardwareInfoEntry::class],
        version = 1,
        exportSchema = false
)
abstract class EteDatabase : RoomDatabase() {

    abstract fun getHardwareInfoDao(): HardwareInfoDao

    companion object {

        private const val TAG = "EteDatabase"

        private var mEteDatabase: EteDatabase? = null
        private var mApp: Application? = null
        private var mDatabasePwd: String = ""
        private var mDatabasePath: String = ""
        private var isInit: Boolean = false

        @JvmStatic
        @JvmOverloads
        fun init(application: Application, mDBPath: String, mPwd: String = "") {
            if (isInit) return
            mApp = application
            mDatabasePath = "${mDBPath}/EteServiceDb.db"
            mDatabasePwd = mPwd
            isInit = true
        }

        @JvmStatic
        @Synchronized
        fun getInstance(): EteDatabase {
            if (mEteDatabase == null) {
//                if (BuildConfig.DEBUG) {
//                    LogUtils.d(TAG, "数据库密码:[$mDatabasePwd]，路径:[$mDatabasePath]")
//                }
//                val pwd = SQLiteDatabase.getBytes(mDatabasePwd.toCharArray())
//                val factory = SupportFactory(pwd)
                mEteDatabase = Room.databaseBuilder(mApp!!, EteDatabase::class.java, mDatabasePath)
                    .allowMainThreadQueries()
                    .addMigrations()
//                    .openHelperFactory(factory)
                    .build()
                // 去除内存安全配置, 该配置会影响数据库速度
                mEteDatabase!!.openHelper.writableDatabase.execSQL("PRAGMA cipher_memory_security = OFF;")
            }
            return mEteDatabase!!
        }
    }

    open fun closeDb() {
        mEteDatabase?.let {
            if (it.isOpen) {
                it.openHelper.close()
            }
        }
        mEteDatabase = null
    }
}